package com.hq.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hq.bean.Article;
import com.hq.service.ArticleService;
import com.hq.util.FileUploadUtil;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class ArticleController {
    @Resource
    private ArticleService articleService;
    @RequestMapping("list.do")
    public String list(Model model, @RequestParam(value = "cpage",defaultValue = "1")Integer cpage,
                     String mohu1, String mohu2){
        Map map = new HashMap();
        map.put("mohu1",mohu1);
        map.put("mohu2",mohu2);
        PageHelper.startPage(cpage,3);
        List list = articleService.list(map);
        PageInfo pageInfo = new PageInfo(list);
        model.addAttribute("pageInfo",pageInfo);
        model.addAttribute("map",map);
        return "list";
    }
    @RequestMapping("del.do")
    @ResponseBody
    public Object del(Integer aid){
        return articleService.del(aid);
    }
    @RequestMapping("add.do")
    @ResponseBody
    public Object add(Article article, @RequestParam("photo")MultipartFile photo, Integer[] tids, HttpSession session){
        if (photo.getOriginalFilename().length()>0){
            String upload = FileUploadUtil.load(session, photo, "upload");
            article.setImg(upload);
        }
        int i = articleService.add(article, tids);
        return i;
    }
    @RequestMapping("toadd.do")
    public String toadd(){
        return "add";
    }
    @RequestMapping("upd.do")
    @ResponseBody
    public Object upd(Article article, @RequestParam("photo")MultipartFile photo, Integer[] tids, HttpSession session){
        if (photo.getOriginalFilename().length()>0){
            String upload = FileUploadUtil.load(session, photo, "upload");
            article.setImg(upload);
        }
        int i = articleService.upd(article, tids);
        return i;
    }
    @RequestMapping("toupd.do")
    public String toupd(Integer aid){
        return "upd";
    }
    @RequestMapping("getById.do")
    @ResponseBody
    public Object getById(Integer aid){
        return articleService.getById(aid);
    }
}
